/// 用户详情页面
/// 
/// 显示用户的详细信息
/// 
/// 作者: Fluttert Team
/// 日期: 2024

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../models/user_model.dart';
import '../../providers/user_provider.dart';
import '../../widgets/common/loading_widget.dart';
import '../../widgets/common/error_widget.dart';

/// 用户详情页面组件
class UserDetailPage extends StatefulWidget {
  /// 用户ID（从路由参数获取）
  final String? userId;
  
  /// 用户对象（可选，如果已有数据可直接传入）
  final UserModel? user;

  const UserDetailPage({
    super.key,
    this.userId,
    this.user,
  });

  @override
  State<UserDetailPage> createState() => _UserDetailPageState();
}

class _UserDetailPageState extends State<UserDetailPage> {
  @override
  void initState() {
    super.initState();
    // 如果有userId但没有user对象，则加载用户详情
    if (widget.userId != null && widget.user == null) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        final userId = int.tryParse(widget.userId!);
        if (userId != null) {
          context.read<UserProvider>().fetchUserById(userId);
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('用户详情'),
      ),
      body: Consumer<UserProvider>(
        builder: (context, provider, child) {
          // 优先使用传入的user对象，否则使用provider中的selectedUser
          final user = widget.user ?? provider.selectedUser;

          // 如果正在加载
          if (provider.isLoading && user == null) {
            return const LoadingWidget();
          }

          // 如果发生错误
          if (provider.error != null && user == null) {
            return CustomErrorWidget(
              message: provider.error!,
              onRetry: widget.userId != null
                  ? () {
                      final userId = int.tryParse(widget.userId!);
                      if (userId != null) {
                        provider.fetchUserById(userId);
                      }
                    }
                  : null,
            );
          }

          // 如果用户不存在
          if (user == null) {
            return Center(
              child: Text(
                '用户不存在',
                style: Theme.of(context).textTheme.bodyLarge,
              ),
            );
          }

          // 显示用户详情
          return SingleChildScrollView(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 用户头像
                Center(
                  child: CircleAvatar(
                    radius: 50,
                    backgroundImage: user.avatar != null
                        ? NetworkImage(user.avatar!)
                        : null,
                    child: user.avatar == null
                        ? Text(
                            user.name[0].toUpperCase(),
                            style: const TextStyle(fontSize: 40),
                          )
                        : null,
                  ),
                ),
                const SizedBox(height: 24),

                // 用户信息卡片
                Card(
                  child: Padding(
                    padding: const EdgeInsets.all(16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        _buildInfoRow('ID', user.id.toString()),
                        const Divider(),
                        _buildInfoRow('姓名', user.name),
                        const Divider(),
                        _buildInfoRow('邮箱', user.email),
                        if (user.age != null) ...[
                          const Divider(),
                          _buildInfoRow('年龄', user.age.toString()),
                        ],
                        if (user.createdAt != null) ...[
                          const Divider(),
                          _buildInfoRow(
                            '创建时间',
                            user.createdAt!.toLocal().toString().split('.')[0],
                          ),
                        ],
                      ],
                    ),
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  /// 构建信息行
  Widget _buildInfoRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 80,
            child: Text(
              label,
              style: const TextStyle(
                fontWeight: FontWeight.bold,
                color: Colors.grey,
              ),
            ),
          ),
          Expanded(
            child: Text(
              value,
              style: const TextStyle(fontSize: 16),
            ),
          ),
        ],
      ),
    );
  }
}

